<?php

namespace app\admin\server;

use think\Cache;
use think\Exception;

class WxworkAccessTokenTxlServer extends QiweiServer
{
    const ACCESS_TOKEN = 'qyapi_weixin_access_token_txl';// 通讯录 同步
    //获取token
    public static function getWxworkAccessToken()
    {
        $access_token = Cache::get(self::ACCESS_TOKEN, null);
        try {
            if(empty($access_token)) {
                self::saveWxworkAccessToken();
                $access_token = Cache::get(self::ACCESS_TOKEN, null);
            } else {
                //有token
                $time = time();
                $access_token = json_decode($access_token, true);
                if($time < $access_token['expires_in']) {
                    return $access_token['access_token'];
                }
                self::saveWxworkAccessToken();
                $access_token = Cache::get(self::ACCESS_TOKEN, null);
            }
            $access_token = json_decode($access_token, true);
            return $access_token['access_token'];
        } catch(Exception $e) {
            throw new Exception($e->getMessage());
        }

    }

    //保存token
    public static function saveWxworkAccessToken()
    {
        $server = new WxworkAccessTokenTxlServer();
        $corpId = $server->corpId;
        $kefu_Secret = $server->txl_Secret;
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' . $corpId . '&corpsecret=' . $kefu_Secret;

        file_put_contents('./getBatchGetByUser.txt','WxworkAccessTokenTxlServer::url::'.$url.PHP_EOL,FILE_APPEND);

        $res = file_get_contents($url);
        if(!$res) {
//            return false;
            throw new Exception('获取token失败');
        }
        $result = json_decode($res, true);
        if($result && $result['errcode'] === 0) {
            $expires_in = (time() + $result['expires_in']) - 300;
            Cache::set(self::ACCESS_TOKEN, json_encode([
                'access_token' => $result['access_token'],
                'expires_in'   => $expires_in,
            ]));
            return $result['access_token'];
        }
//            return false;
        throw new Exception($result['errmsg']);
    }
}